import { cartList, changeCount, delSelect } from '@/api/cart'
export default {
    namespaced: true,
    state() {
        return {
            cartList: [],

        }
    },
    mutations: {
        setCartList(state, newList) {
            state.cartList = newList
        },
        toggleCheck(state, goods_id) {
            const goods = state.cartList.find(item => item.goods_id == goods_id)
            goods.isChecked = !goods.isChecked
        },
        toggleItemCheck(state, checked) {
            state.cartList.forEach(item => item.isChecked = checked)
        }
    },
    actions: {
        async getCartAction(context) {
            const { data } = await cartList()
            data.list.forEach(item => { item.isChecked = true })
            context.commit('setCartList', data.list)
        },
        async changeCount(context, obj) {
            await changeCount(obj.goodsId, obj.goodsNum, obj.goodsSkuId)
            const item = context.state.cartList.find((item) => item.goods_id == obj.goodsId)
            item.goods_num = obj.goodsNum
        },
        async delSelect(context) {
            const selCartList = context.getters.selCartList
            const cartIds = selCartList.map(item => item.id)
            await delSelect(cartIds)
            context.dispatch('getCartAction')
        }
    },
    getters: {
        //求所有的商品累加总数
        cartTotal(state) {
            return state.cartList.reduce((sum, item) => sum + item.goods_num, 0)
        },
        selCartList(state) {
            return state.cartList.filter(item => item.isChecked)
        },
        //选中的商品总数
        selCount(state, getters) {
            return getters.selCartList.reduce((sum, item) => sum + item.goods_num, 0)
        },
        //选中的总价
        selPrice(state, getters) {
            return getters.selCartList.reduce((sum, item) => sum + item.goods_num * item.goods.goods_price_min, 0).toFixed(2)
        },
        isAllCheck(state) {
            return state.cartList.every(item => item.isChecked)
        }
    }
}